/* 组件相关公共类 */
export * from './data'
export * from './class'
export * from './dom'
export * from './file'
export * from './compositions'
export * from './directives'
export { default as EffectLock } from './EffectLock'

/**
 * 创建 id
 * @return {string}
 */
export const createId = () => Math.random().toString(32).slice(2)

/** 延时执行函数 Promise */
export async function awaitTimeout<T extends () => void>(callback?: T, ms?: number): Promise<ReturnType<T>>

export async function awaitTimeout<T extends () => void>(ms?: number, callback?: T): Promise<ReturnType<T>>

export async function awaitTimeout<T extends () => void>(
  msOrCallback?: T | number,
  callbackOrMs?: number | T
): Promise<ReturnType<T>> {
  const ms =
    (typeof msOrCallback === 'number' && msOrCallback) || (typeof callbackOrMs === 'number' && callbackOrMs) || 0
  const callback =
    (typeof msOrCallback === 'function' && msOrCallback) ||
    (typeof callbackOrMs === 'function' && callbackOrMs) ||
    undefined

  return new Promise((resolve, reject) => {
    setTimeout(async () => {
      try {
        const res = (await callback?.()) as ReturnType<T>
        resolve(res)
      } catch (e) {
        reject(e)
      }
    }, ms)
  })
}

type PromiseResolve = (value?: any) => void

type PromiseReject = (reason?: any) => void

/** 创建 Promise，用于在 Promise 外部 resolve\ */
export function createPromise() {
  let resolve: PromiseResolve | null = null
  let reject: PromiseReject | null = null

  const promise = new Promise<any>((res, rej) => {
    resolve = res
    reject = rej
  })

  return { promise, resolve: resolve as unknown as PromiseResolve, reject: reject as unknown as PromiseReject }
}
